package fi.foyt.cs.persistence.dao.task;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.task.GeneralTaskLevel;

public class GeneralTaskLevelDAO extends GenericDAO<GeneralTaskLevel> {

  public GeneralTaskLevel create(Long generalTaskId, Long taskRewardsId, Long taskRequirementsId, Integer levelNumber) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      GeneralTaskLevel generalTaskLevel = new GeneralTaskLevel();
      generalTaskLevel.setGeneralTaskId(generalTaskId);
      generalTaskLevel.setTaskRewardsId(taskRewardsId);
      generalTaskLevel.setTaskRequirementsId(taskRequirementsId);
      generalTaskLevel.setLevelNumber(levelNumber);
      entityManager.persist(generalTaskLevel);
      entityManager.getTransaction().commit();
      return generalTaskLevel;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  @SuppressWarnings("unchecked")
  public List<GeneralTaskLevel> listByGeneralTaskId(Long generalTaskId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select o from GeneralTaskLevel o where generalTaskId = :generalTaskId");
    query.setParameter("generalTaskId", generalTaskId);
    return query.getResultList();
  }
  
  @SuppressWarnings("unchecked")
  public List<GeneralTaskLevel> listBySceneCategoryId(Long sceneCategoryId) {
    EntityManager entityManager = getEntityManager();
    
    Query query = entityManager.createQuery("select t.generalTaskLevelId from GeneralTaskLevelCategory t where t.sceneCategoryId = :sceneCategoryId");
    query.setParameter("sceneCategoryId", sceneCategoryId);
    List<Long> generalTaskLevelIds = query.getResultList();
    
    if (generalTaskLevelIds.size() > 0) {
      query = entityManager.createQuery("select t from GeneralTaskLevel t where t.id in (" + StringUtils.join(generalTaskLevelIds.toArray(), ',') + ")");
      return query.getResultList();
    } else {
      return new ArrayList<GeneralTaskLevel>();
    }
  }
  
}
